package com.amanda.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.amanda.constant.MessageConstant;
import com.amanda.constant.RedisMessageConstant;
import com.amanda.entity.Result;
import com.amanda.pojo.Order;
import com.amanda.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author amanda
 * @Description 预约信息提交
 */

@RequestMapping("/order")
@RestController
public class OrderController {
    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;

    // 提交预约信息
    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map) {
        // 从map中取出验证码，进行比对
        String telephone = (String) map.get("telephone");
        // 获取redis中的验证码
        String codeInRedis = jedisPool.getResource().get(
                telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        // 比对
        if (codeInRedis == null || !codeInRedis.equals(validateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }else {
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result = null;
            try {
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            if (result.isFlag()) {
                // 预约成功，模拟发送短信提示
                String orderDate = (String) map.get("orderDate");
                System.out.println(orderDate + " 已预约成功，请提前10分钟到达！");
            }
            return result;
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS, map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
